package com.pearlsoft.webapp.core.executor;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

import com.pearlsoft.commons.utils.ClassUtil;
import com.pearlsoft.webapp.core.dataset.DataSet;
import com.pearlsoft.webapp.core.dataset.DataSetFactory;
import com.pearlsoft.webapp.core.dataset.Query;
import com.pearlsoft.webapp.core.dataset.QueryHandler;
import com.pearlsoft.webapp.core.dataset.QueryHandlerFactory;

/**
 * 
 * QueryExecutor
 * 
 * @Creator haitingr
 * @Create-DateTime 2011-10-25
 */
public class QueryExecutor extends AbstractExecutor {

	protected static final Log logger = LogFactory.getLog(QueryExecutor.class);

	protected QueryHandlerFactory queryHandlerFactory;

	protected DataSetFactory dataSetFactory = null;

	protected String encoding = "UTF-8";

	public byte[] execute(byte[] message) throws Exception {
		Query query = new Query();
		ObjectMapper om = new ObjectMapper();
		query = om.readValue(message, query.getClass());
		QueryHandler handler = this.queryHandlerFactory.create(query.getHandler());
		DataSet ds = this.dataSetFactory.create(query.getDatasetName());
		handler.setHttpServletRequest(this.getHttpServletRequest());
		handler.setHttpServletResponse(this.getHttpServletResponse());
		Method method = ClassUtil.getMethodIfAvailable(handler.getClass(), query.getHandlerMethod(), new Class<?>[] {
				Query.class, DataSet.class });
		method.invoke(handler, new Object[] { query, ds });
		byte[] values = ds.toJson();
		logger.debug("dataset value:" + new String(values, "UTF-8"));
		return values;
	}

	public void setQueryHandlerFactory(QueryHandlerFactory queryHandlerFactory) {
		this.queryHandlerFactory = queryHandlerFactory;
	}

	public void setDataSetFactory(DataSetFactory dataSetFactory) {
		this.dataSetFactory = dataSetFactory;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

}
